package com.css.zfzx.sjcj.modules.hddcGeoProfileLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.repository.HddcGeoprofilelineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.repository.HddcGeoprofilelineRepository;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.repository.entity.HddcGeoprofilelineEntity;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.service.HddcGeoprofilelineService;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.viewobjects.HddcGeoprofilelineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeoProfileLine.viewobjects.HddcGeoprofilelineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcGeoprofilelineServiceImpl implements HddcGeoprofilelineService {

	@Autowired
    private HddcGeoprofilelineRepository hddcGeoprofilelineRepository;
    @Autowired
    private HddcGeoprofilelineNativeRepository hddcGeoprofilelineNativeRepository;

    @Override
    public JSONObject queryHddcGeoprofilelines(HddcGeoprofilelineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeoprofilelineEntity> hddcGeoprofilelinePage = this.hddcGeoprofilelineNativeRepository.queryHddcGeoprofilelines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeoprofilelinePage);
        return jsonObject;
    }


    @Override
    public HddcGeoprofilelineEntity getHddcGeoprofileline(String id) {
        HddcGeoprofilelineEntity hddcGeoprofileline = this.hddcGeoprofilelineRepository.findById(id).orElse(null);
         return hddcGeoprofileline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeoprofilelineEntity saveHddcGeoprofileline(HddcGeoprofilelineEntity hddcGeoprofileline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeoprofileline.setUuid(uuid);
        hddcGeoprofileline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeoprofileline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeoprofileline.setIsValid("1");
        hddcGeoprofileline.setQualityinspectionStatus("0");
        hddcGeoprofileline.setExtends10("1");
        this.hddcGeoprofilelineRepository.save(hddcGeoprofileline);
        return hddcGeoprofileline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeoprofilelineEntity> saveHddcGeoprofilelineList(List<HddcGeoprofilelineEntity> list) {
        for (HddcGeoprofilelineEntity hddcGeoprofileline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeoprofileline.setUuid(uuid);
            hddcGeoprofileline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeoprofileline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeoprofileline.setIsValid("1");
            hddcGeoprofileline.setQualityinspectionStatus("0");
            hddcGeoprofileline.setExtends10("1");
        }

        return hddcGeoprofilelineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeoprofilelineEntity updateHddcGeoprofileline(HddcGeoprofilelineEntity hddcGeoprofileline) {
        HddcGeoprofilelineEntity entity = hddcGeoprofilelineRepository.findById(hddcGeoprofileline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeoprofileline);
        hddcGeoprofileline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeoprofileline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeoprofilelineRepository.save(hddcGeoprofileline);
        return hddcGeoprofileline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeoprofilelines(List<String> ids) {
        List<HddcGeoprofilelineEntity> hddcGeoprofilelineList = this.hddcGeoprofilelineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeoprofilelineList) && hddcGeoprofilelineList.size() > 0) {
            for(HddcGeoprofilelineEntity hddcGeoprofileline : hddcGeoprofilelineList) {
                hddcGeoprofileline.setIsValid("0");
                hddcGeoprofileline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeoprofileline.setUpdateTime(new Date());
                this.hddcGeoprofilelineRepository.save(hddcGeoprofileline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeoprofilelineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeoprofilelineEntity> yhDisasterEntities = hddcGeoprofilelineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeoprofilelineVO> list=new ArrayList<>();
        for (HddcGeoprofilelineEntity entity:yhDisasterEntities) {
            HddcGeoprofilelineVO yhDisasterVO=new HddcGeoprofilelineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地质剖面线-线","地质剖面线-线",HddcGeoprofilelineVO.class,"地质剖面线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeoprofilelineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeoprofilelineVO.class, params);
            List<HddcGeoprofilelineVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeoprofilelineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeoprofilelineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcGeoprofilelineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeoprofilelineEntity yhDisasterEntity = new HddcGeoprofilelineEntity();
            HddcGeoprofilelineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeoprofileline(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeoprofilelineEntity> hddcGeoprofilelineList = this.hddcGeoprofilelineRepository.queryHddcGeoprofilelinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeoprofilelineList) && hddcGeoprofilelineList.size() > 0) {
            for(HddcGeoprofilelineEntity hddcGeoprofileline : hddcGeoprofilelineList) {
                hddcGeoprofileline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeoprofileline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeoprofileline.setIsValid("0");
                this.hddcGeoprofilelineRepository.save(hddcGeoprofileline);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeoprofilelineEntity> hddcGeoprofilelineList = this.hddcGeoprofilelineRepository.queryHddcGeoprofilelinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeoprofilelineList) && hddcGeoprofilelineList.size() > 0) {
            for(HddcGeoprofilelineEntity hddcGeoprofileline : hddcGeoprofilelineList) {
                hddcGeoprofileline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeoprofileline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeoprofileline.setIsValid("0");
                this.hddcGeoprofilelineRepository.save(hddcGeoprofileline);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("FieldID")){
            str+="FieldID,";
        }
        if(!set.contains("Name")){
            str+="Name,";
        }
        if(!set.contains("ProfileType")){
            str+="ProfileType,";
        }
        if(!set.contains("Purpose")){
            str+="Purpose,";
        }
        if(!set.contains("Scale")){
            str+="Scale,";
        }
        if(!set.contains("GeoProfile_AIID")){
            str+="GeoProfile_AIID,";
        }
        if(!set.contains("GeoProfile_ARWID")){
            str+="GeoProfile_ARWID,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;

    }

    @Override
    public void savehddcGeoprofilelineServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcGeoprofilelineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeoprofilelineEntity data = new HddcGeoprofilelineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setFieldid(obs.get(2).toString());
                data.setName(obs.get(3).toString());
                data.setProfiletype(Integer.valueOf(obs.get(4).toString()));
                data.setPurpose(obs.get(5).toString());
                data.setScale(Integer.valueOf(obs.get(6).toString()));
                data.setGeoprofileAiid(obs.get(7).toString());
                data.setGeoprofileArwid(obs.get(8).toString());
                data.setCommentInfo(obs.get(9).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeoprofilelineList(datas);
        }
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeoprofilelineEntity> hddcGeoprofilelineList = this.hddcGeoprofilelineRepository.queryHddcGeoprofilelineByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeoprofilelineList) && hddcGeoprofilelineList.size() > 0) {
            hddcGeoprofilelineRepository.deleteAll(hddcGeoprofilelineList);
        }
    }


    @Override
    public List<HddcGeoprofilelineEntity> findAll() {
        List<HddcGeoprofilelineEntity> list=this.hddcGeoprofilelineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeoprofilelineRepository.deleteFileData( provinceName, cityName, areaName, savefilename);
    }
}
